<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\delivery\Channel;
use app\common\model\delivery\Driver;
use app\common\model\delivery\ChannelGird;
use app\common\model\delivery\ChannelOrder;
use app\common\model\delivery\MonthBill;
use app\common\model\delivery\Seller;
use app\common\model\delivery\Customer;
use app\common\model\delivery\CustomerRegister;
use app\common\model\delivery\SellerCommission;
use app\common\model\Qrcode;
use app\common\model\QrcodeScan;
use app\common\model\Third;
use app\common\service\msg\WechatMsg;
use think\annotation\route\Get;
use think\annotation\route\Group;
use app\common\model\User as UserModel;
use think\annotation\route\Post;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\facade\Db;
use think\Response;

#[Group("user")]
class User extends Api
{
    protected $noNeedLogin = ['wxlogin','getMobile','binduser'];

    #[Get('auth')]
    public function auth()
    {
        $channel= Channel::where("FIND_IN_SET({$this->auth->id},user_id)")->find();
        $is_admin=$channel?1:0;
        $driver=Driver::where(['user_id'=>$this->auth->id,'status'=>'normal'])->find();
        $is_driver=$driver?1:0;
        $seller=Seller::where(['user_id'=>$this->auth->id,'status'=>'normal'])->find();
        $is_seller=$seller?1:0;
        $customer=Customer::withJoin(['channel'],'right')->with(['goods','address'])->where("FIND_IN_SET({$this->auth->id},customer.user_id)")->select();
        $is_customer=count($customer)?1:0;
        $register_id=0;
        if(!$is_customer){
            $register=CustomerRegister::where(['user_id'=>$this->auth->id,'status'=>0])->find();
            $register_id=$register?$register->id:0;
        }else{
            foreach ($customer as $key=>$value){
                if($value['customer_type']=='family'){
                    $customer[$key]['name']=$value['address'];
                }
                $customer[$key]['goods']=Customer::parseGoods($value['goods'],$value['channel']);
            }
        }
        $this->success('',compact('is_admin','is_driver','is_seller','is_customer','customer','register_id'));
    }

    #[Get('userinfo')]
    public function userinfo()
    {
        $user=$this->auth->userinfo();
        $page=$this->request->get('page');
        if($page=='shop'){
            $customer_id=$this->request->get('customer_id');
            $start=strtotime(date('Y-m-01'));
            $month_buy=ChannelOrder::where(['customer_id'=>$customer_id,'is_cancel'=>0])->whereRaw("is_pay=1 or (pay_type='delivery' and is_pay=0)")->where('createtime','between',[$start,time()])->field('sum(total_money) as total_money,count(1) as count')->find();
            $customer=Customer::with(['gird'])->find($customer_id);
            $last_month_yuefu='';
            $this_month_yuefu='';
            if($customer->settle_type=='month'){
                $lastmonth=MonthBill::getLastMonthOrderDate($customer);
                $last_month_yuefu=ChannelOrder::where(['customer_id'=>$customer_id,'is_cancel'=>0,'pay_type'=>'month'])->where('createtime','between',$lastmonth)->field('sum(total_money) as total_money,count(1) as count,0 as is_pay')->find();
                //上月账单
                $month=date('Y-m',strtotime('-1 month'));
                $bill=MonthBill::where(['customer_id'=>$customer_id,'month'=>$month])->find();
                $last_month_yuefu['bill']=$bill;
                $thismonth=MonthBill::getThisMonthOrderDate($customer);
                $this_month_yuefu=ChannelOrder::where(['customer_id'=>$customer_id,'is_cancel'=>0,'pay_type'=>'month'])->where('createtime','between',$thismonth)->field('sum(total_money) as total_money,count(1) as count')->find();
            }
            $this->success('',compact('user','month_buy','last_month_yuefu','this_month_yuefu'));
        }
        if($page=='admin'){
            $channel= Channel::where("FIND_IN_SET({$this->auth->id},user_id)")->find();
            $seller='';
            $role='admin';
            if(!$channel){
                $seller=Seller::where(['user_id'=>$this->auth->id])->find();
                if(!$seller){
                    $this->error('没有操作权限！');
                }
                $channel=Channel::find($seller->channel_id);
                $role='seller';
            }
            if(!$channel){
                $this->error('未知贸易商！');
            }
            //非销售经理展示网格和司机数量
            $gird='';
            $driver='';
            $jingli='';
            $jiesuan='';
            $coupon='';
            $shouyi=[
                'all_money'=>0,
                'today_money'=>0
            ];
            $wuliu=[
                'total'=>0,
                'receive'=>0
            ];
            if($role=='admin'){
                $prefix=getDbPrefix();
                $gird=ChannelGird::where(['channel_id'=>$channel->id])->count();
                $driver=Driver::where(['channel_id'=>$channel->id])->count();
                $jingli=Seller::where(['channel_id'=>$channel->id])->count();
                $shouyi['all_money']=ChannelOrder::where(['channel_id'=>$channel->id,'is_cancel'=>0])->sum('total_money');
                $start=strtotime(date('Y-m-d 00:00:00'));
                $end=strtotime(date('Y-m-d 23:59:59'));
                $shouyi['today_money']=ChannelOrder::where(['channel_id'=>$channel->id,'is_cancel'=>0])->whereBetween('createtime',[$start,$end])->sum('total_money');
                $wuliu['total']=ChannelOrder::where(['channel_id'=>$channel->id,'is_cancel'=>0,'delivery_day'=>date('Y-m-d')])->count();
                $wuliu['receive']=ChannelOrder::where(['channel_id'=>$channel->id,'is_cancel'=>0,'delivery_day'=>date('Y-m-d')])->whereNotNull('receive_time')->count();
                $sql="
                    SELECT 
                    coupon.type,count(1) as count,
                    SUM(list.balance) as balance,
                    SUM(list.total-list.take) as total 
                    FROM {$prefix}coupon_list list,{$prefix}coupon coupon
                    where list.coupon_id=coupon.id and list.total>list.take and list.channel_id={$channel->id}
                    GROUP BY coupon.type
                ";
                $couponlist=Db::query($sql);
                $coupon=[];
                foreach ($couponlist as $value){
                    $coupon[$value['type']]=$value;
                }
            }
            if($role=='seller'){
                $shouyi['all_money']=SellerCommission::where(['seller_id'=>$seller->id])->sum('money');
                $start=strtotime(date('Y-m-d 00:00:00'));
                $end=strtotime(date('Y-m-d 23:59:59'));
                $shouyi['today_money']=SellerCommission::where(['seller_id'=>$seller->id])->whereBetween('createtime',[$start,$end])->sum('money');
                $jiesuan=0;
            }
            $apply=CustomerRegister::where(function ($query) use ($channel,$seller){
                $query->where('channel_id','=',$channel->id);
                $query->where('status','=',0);
                if($seller){
                    $query->where('seller_id','=',$seller->id);
                }
            })->select();
            foreach ($apply as $key=>$value){
                $apply[$key]['info']=json_decode($value['info'],true);
            }
            $store_num=Customer::where(function ($query) use ($channel,$seller){
                $query->where('channel_id','=',$channel->id);
                if($seller){
                    $query->where('seller_id','=',$seller->id);
                }
            })->count();
            $store_month_num=Customer::where(function ($query) use ($channel,$seller){
                $query->where('channel_id','=',$channel->id);
                //当月新增
                $start=strtotime(date('Y-m-01'));
                $query->where('createtime','between',[$start,time()]);
                if($seller){
                    $query->where('seller_id','=',$seller->id);
                }
            })->count();
            $store=[
                'store_num'=>$store_num,
                'store_month_num'=>$store_month_num
            ];
            $this->success('',compact('user','role','channel','coupon','gird','driver','apply','store','jingli','jiesuan','shouyi','wuliu'));
        }
        if($page=='driver'){
            $drivers=Driver::withJoin(['channel'],'inner')->where(['driver.user_id'=>$this->auth->id,'driver.status'=>'normal'])->select();
            if(count($drivers)==0){
                $this->error('你不是司机！');
            }
            $channel=[];
            foreach ($drivers as $value){
                $channel[]=$value['channel'];
            }
            $girdids=Driver::getGirdIds($drivers,$this->auth->id);
            if(count($girdids)==0){
                $this->error('你还没有绑定网格！');
            }
            $customer=Customer::whereIn('gird_id',$girdids)->count();
            $this->success('',compact('user','channel','customer'));
        }
    }

    #[Get('binduser')]
    public function binduser()
    {
        $qrcode_id=$this->request->get('qrcode_id');
        $qrcode=Qrcode::find($qrcode_id);
        $foreign_key=json_decode($qrcode->foreign_key,true);
        $channel=$foreign_key['channel'];
        $avatar='/static/header.png';
        $nickname='';
        if($this->auth->isLogin()){
            $avatar=$this->auth->avatar;
            $nickname=$this->auth->nickname;
        }
        $this->success('',compact('avatar','nickname','channel'));
    }

    #[Get('getChannel')]
    public function getChannel()
    {
        $qrcode_id=$this->request->get('qrcode_id');
        $channel=Channel::getChannelAndSeller($qrcode_id);
        if(!$channel){
            $this->error('系统未设置默认服务商！');
        }
        $this->success('',$channel);
    }

    #[Post('wxlogin')]
    public function wxlogin()
    {
        $code=$this->request->post('code');
        $qrcode_id=$this->request->post('qrcode_id');
        $config=[
            'appid'=>site_config("goodsdelivery.miniapp_id"),
            'appsecret'=>site_config("goodsdelivery.miniapp_secret")
        ];
        $mini = new \WeMini\Crypt($config);
        $data = $mini->session($code);
        $openid=$data['openid'];
        $unionid=isset($data['unionid'])?$data['unionid']:'';
        $avatar=$this->request->post('avatar');
        $nickname=$this->request->post('nickname');
        $mobile=$this->request->post('mobile');
        //判断是否启用账号绑定
        $third=Third::connect(Third::PLATFORM('微信小程序'), compact('openid', 'unionid', 'avatar', 'nickname', 'mobile'));
        $this->auth->loginByThirdPlatform(Third::PLATFORM('微信小程序'),$third);
        $token=$this->auth->getToken();
        $userinfo=$this->auth->userinfo();
        if($qrcode_id){
            $qrcode=Qrcode::find($qrcode_id);
            //生成的扫码记录表，可以在用户注册时，查询该表从而绑定推荐人
            QrcodeScan::create([
                'openid'=>$openid,
                'unionid'=>$unionid,
                'qrcode_id'=>$qrcode_id,
                'foreign_key'=>$qrcode->foreign_key,
                'type'=>$qrcode->type,
            ]);
        }
        $this->success('登录成功',compact('token','userinfo'));
    }

    #[Post('getMobile')]
    public function getMobile()
    {
        $code=$this->request->post('code');
        $config=[
            'appid'=>site_config("goodsdelivery.miniapp_id"),
            'appsecret'=>site_config("goodsdelivery.miniapp_secret")
        ];
        $mini = new \WeMini\Crypt($config);
        $result=$mini->getPhoneNumber($code);
        $this->success('',$result['phone_info']['phoneNumber']);
    }

    #[Post('register')]
    public function register()
    {
        $postdata=$this->request->post();
        $mobile=$postdata['info']['mobile'];
        $code=$postdata['code'];
        if(!$code){
            $this->error('请输入手机验证码');
        }
        $cachecode=Cache::get('sms_code_'.$mobile);
        if($code!=$cachecode){
            $this->error('验证码不正确');
        }
        $register=false;
        if($postdata['id']){
            $register=CustomerRegister::find($postdata['id']);
            if($register->status==1){
                $this->error('店铺已经审核通过了，禁止修改');
            }
        }
        if(!$register){
            $register=new CustomerRegister();
        }
        $postdata['user_id']=$this->auth->id;
        $postdata['createtime']=date('Y-m-d H:i:s',time());
        $userinfo=$this->auth->userinfo();
        if(!$userinfo['mobile']){
            UserModel::where(['id'=>$userinfo['id']])->update(['mobile'=>$mobile]);
        }
        $info=$postdata['info'];
        $postdata['info']=json_encode($postdata['info'],JSON_UNESCAPED_UNICODE);
        $register->save($postdata);
        $register_id=$register->id;
        $user_ids=[];
        $seller_id=$postdata['seller_id'];
        if($seller_id){
            $seller=Seller::find($seller_id);
            $user_ids[]=$seller->user_id;
        }
        $channel_id=$postdata['channel_id'];
        $channel=Channel::find($channel_id);
        $user_ids=array_merge($user_ids,explode(',',$channel->user_id));
        foreach ($user_ids as $user_id){
            if(!$user_id){
                continue;
            }
            WechatMsg::newCustomerApply($user_id,$register_id,$info);
        }
        $this->success('注册成功，请等待管理员审核');
    }

    #[Get('getregister')]
    public function getregister($id)
    {
        $customer=CustomerRegister::find($id);
        if($this->auth->id!=$customer->user_id){
            $this->error('非法操作！');
        }
        if($customer->status){
            $this->error('你的申请已经审核通过了！');
        }
        $customer->info=json_decode($customer['info'],true);
        $customer->channel=Channel::find($customer->channel_id);
        if($customer->seller_id){
            $customer->seller=Seller::find($customer->seller_id);
        }
        $this->success('',$customer);
    }

    #[Get('getcustomer')]
    public function getcustomer($id)
    {
        $customer=Customer::with(['channel','seller'])->find($id);
        if(!in_array($this->auth->id,explode(',',$customer->user_id))){
            $this->error('非法操作！');
        }
        $this->success('',$customer);
    }
}
